<?php

/**
 * 教师管理
 */

namespace app\tdadmin\controller;

use app\common\controller\AdminBaseController;
use app\common\model\CollegeModel;
use app\common\model\SpecialtyModel;
use app\common\model\TeacherModel;
use think\Db;
use PHPExcel_IOFactory;
use PHPExcel;
use think\Loader;


class TeacherController extends AdminBaseController
{
    public function index()
    {
        return $this->fetch();
    }

    public function getUsers()
    {
        $mobile = $this->request->param('key.phone', '');
        $map[] = ['phone', 'like', '%' . $mobile . '%'];

        $count = TeacherModel::where($map)->order('id desc')->count();

        $page = $this->request->param('page/d', 1, 'intval');
        $limit = $this->request->param('limit/d', 10, 'intval');

        $lists = TeacherModel::where($map)->order("id desc")->limit(($page - 1) * $limit, $limit)->all();

        $res['code'] = 0;
        $res['msg'] = 'success';
        $res['data'] = $lists;
        $res['count'] = $count;
        return $res;
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $res['code'] = 1;
            $data = $this->request->param('');

            if ($data['login_pass'] != $data['upass']) {
                $res['msg'] = '两次密码输入不一致';
            }

            $teacher_no = $data['teacher_no'];
            $phone = $data['phone'];
            $info = Db::name("teacher")->where('teacher_no', $teacher_no)->whereOr("phone", $phone)->count();

            if ($info) {
                $res['msg'] = '该工号或手机号已被录入';
                $res['code'] = 0;
            } else {
                $data['password'] = password($data['login_pass']);
                unset($data['upass']);
                unset($data['login_pass']);
                unset($data['newTag']);
                unset($data['imagelabels']);
                unset($data['newtext']);
                unset($data['selectedtext']);
                unset($data['existedtext']);

                $admin_id = Db::name('teacher')->insertGetId($data);
                if ($admin_id) {
                    $res['msg'] = '添加成功';
                }
            }
            addLog("添加了新老师：".$data['teacher_no'],Db::getLastSql());

            return $res;
        } else {

            $colleges = Db::name("college")->where("status", 1)
                ->order("id asc")
                ->all();
            $tags = Db::name("tags")->where("type", 0)->all();
            $this->assign("tagList", $tags);
            $this->assign("colleges", $colleges);
            $this->assign('specialties', []);
            return $this->fetch();
        }
    }

    public function getSpecialties()
    {
        if ($this->request->isPost()) {
            $college_id = $this->request->param('college_id');
            if ($college_id) {
                $specialties = Db::name("specialty")->where('college_id', $college_id)->where('status', 1)->order('id asc')->all();
                $data['code'] = 0;
                $data['msg'] = '成功';
                $data['data'] = $specialties;
            } else {
                $data['code'] = 0;
                $data['msg'] = '成功';
                $data['data'] = [];
            }
            return $data;
        }
    }

    public function addTag()
    {
        if ($this->request->isPost()) {
            $tag = $this->request->param('newTag');

            $find = Db::name("tags")->where("tag", $tag)->where('type', 0)->find();
            if ($find) {
                $data['code'] = 1;
                $data['msg'] = '已在该标签';
            } else {
                $tid = Db::name("tags")->insertGetId(['tag' => $tag, 'type' => 0]);
                $newTag = Db::name("tags")->where('id', $tid)->find();
                addLog("添加了标签：".$newTag['tag'],Db::getLastSql());

                $data['code'] = 0;
                $data['msg'] = '成功';
                $data['data'] = $newTag;
                $data['tid'] = $tid;
            }
            return $data;
        }
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param('');
            unset($data['upass']);
            unset($data['login_pass']);
            unset($data['newTag']);
            unset($data['imagelabels']);
            unset($data['newtext']);
            unset($data['selectedtext']);
            unset($data['existedtext']);

            if (isset($data['password']) && $data['password'] != null){
                $data['password'] = password($data['password']);
            }

            $data['update_time'] = date('Y-m-d H:i:s',time());
            $result = Db::name("teacher")->update($data);
            addLog("修改了老师信息：".$data['teacher_no'],Db::getLastSql());

            if ($result !== false) {
                $this->success("修改成功");
            } else {
                $this->error("修改失败");
            }
        } else {

            $id = input("param.id");

            $data = Db::name("teacher")->get($id);


            $colleges = Db::name("college")->where("status", 1)
                ->order("id asc")
                ->all();
            $tags = Db::name("tags")->where("type", 0)->all();
            $specialties = Db::name("specialty")->where('college_id', $data['college'])->all();

            $selectedTag = explode(",", $data['tag_text']);
            $this->assign("selectedTag", $selectedTag);
            $this->assign("tagList", $tags);
            $this->assign("colleges", $colleges);
            $this->assign("specialties", $specialties);
            $this->assign(["data" => $data]);

            return $this->fetch();
        }
    }

    public function lookuser()
    {
        $id = input("param.id");

        $data = Db::name("teacher")->get($id);


        $colleges = Db::name("college")->where("id", $data['college'])->find();
        $tags = Db::name("tags")->where("type", 0)->all();
        $specialties = Db::name("specialty")->where('id', $data['specialty'])->find();
        $selectedTag = explode(",", $data['tag_text']);
        $this->assign("selectedTag", $selectedTag);
        $this->assign("tagList", $tags);
        $this->assign("college", $colleges['college_name']);
        $this->assign("specialty", $specialties['specialty_name']);
        $this->assign(["data" => $data]);

        return $this->fetch();
    }

    public function getSelectedTagList()
    {
        $id = input("param.id");
        if ($id) {
            $teacher = Db::name("teacher")->get($id);
            $allTags = Db::name("tags")->field("id,tag")->all();
            $data['code'] = 1;
            $data['tags'] =explode(",", $teacher['tag_text']);
            $data['allTags'] = $allTags;
        } else {
            $allTags = Db::name("tags")->field("id,tag")->all();
            $data['code'] = 1;
            $data['tags'] = [];
            $data['allTags'] = $allTags;
        }
        return $data;
    }

    public function delAdmin()
    {
        $id = input("param.id");

        Db::name("member")->delete($id);

        $this->success("删除成功");
    }

    //检测工号是否重复
    public function checkNo()
    {
        $teacher_no = $this->request->param('teacher_no');

        $data['code'] = 1;
        $data['msg'] = '该工号可用！';

        if (TeacherModel::where('teacher_no', $teacher_no)->find()) {
            $data['code'] = 0;
            $data['msg'] = '该工号已存在';
        }

        return $data;
    }


    //检测手机号是否重复
    public function checkPhone()
    {
        $phone = $this->request->param('phone');

        $data['code'] = 1;
        $data['msg'] = '该手机号可用！';

        if (TeacherModel::where('phone', $phone)->find()) {
            $data['code'] = 0;
            $data['msg'] = '该手机号已存在';
        }

        return $data;
    }

    public function delTeacher()
    {
        $id = $this->request->param('id');

        $data['code'] = 1;
        $data['msg'] = '删除成功！';
        $teacher = TeacherModel::where('id', $id)->find();

        if (!$teacher) {
            $data['code'] = 0;
            $data['msg'] = '无该教师信息';
        } else {
            TeacherModel::where('id', $id)->delete();
            addLog("删除了老师信息：".$teacher['teacher_no'],Db::getLastSql());

        }

        return $data;
    }


    /**
     * 更新字段
     */
    public function updateField()
    {
        return parent::fieldUpdate(new TeacherModel());
    }



    /**
     * 显示/开启操作
     *
     * @author Eric ieyangxiaoguo@126.com
     *         @date 2017年11月26日
     */
    public function doSwitch()
    {
        return parent::switchOperate(new TeacherModel());
    }


    public function insert(){
        return $this->fetch();
    }

    /*
     * 批量导入代理商详情
     */
    public function insertTeacher()
    {
        if (request()->ispost()) {
            // 获取表单上传文件
            $file = $this->request->file('file');
            if (empty($file)) {
                $this->error('请选择上传文件！');
            } else {
                //文件位置
                $moveUrl = ROOT_PATH .  DS . 'upload/files/teachers/';
                //移动文件
                $info = $file->validate(['size' => 12428800, 'ext' => 'xls,xlsx'])->rule('uniqid')->move($moveUrl);
                if ($info) {
                    // 成功上传后 获取上传信息
                    $file_name = $moveUrl . DS . $info->getFilename();
                    //导入

                    require ROOT_PATH. DS .'../vendor/codeplex/phpexcel/PHPExcel.php';
                    $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));//判断导入表格后缀格式
                    if ($extension == 'xlsx') {
                        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
                        $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                    } else if ($extension == 'xls') {
                        $objReader = PHPExcel_IOFactory::createReader('Excel5');
                        $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
                    }
                    $sheet = $objPHPExcel->getSheet(0);
                    $highestRow = $sheet->getHighestRow();//取得总行数
                    $highestColumn = $sheet->getHighestColumn(); //取得总列数
                    $num = 0;
                    $result = "";
                    for ($i = 2; $i <= $highestRow; $i++) {
                        $map['teacher_no'] = $objPHPExcel->getActiveSheet()->getCell("A" . $i)->getValue();
                        $map['real_name'] = $objPHPExcel->getActiveSheet()->getCell("B" . $i)->getValue();
                        $map['phone'] = $objPHPExcel->getActiveSheet()->getCell("C" . $i)->getValue();
                        $map['phone'] =  $map['phone'] ?  $map['phone'] : '';
                        $college = CollegeModel::where('college_name',$objPHPExcel->getActiveSheet()->getCell("D" . $i)->getValue())->find();
                        if ($college){
                            $map['college'] = $college['id'];
                        }
                        $specialty = SpecialtyModel::where('specialty_name', $objPHPExcel->getActiveSheet()->getCell("E" . $i)->getValue())->find();
                        if ($specialty){
                            $map['specialty'] = $specialty['id'];
                        }
                        $password = $objPHPExcel->getActiveSheet()->getCell("F" . $i)->getValue();
                        $password = $password ? $password : "sk123456";
                        $map['password'] = password($password);
                        $map['status'] = 1;
                        $uid = Db::name('teacher')->insertGetId($map);
                        addLog("批量导入老师信息",Db::getLastSql()); // 添加日志
                        if ($uid) {
                            $num++;
                        } else {
                            break;
                        }
                    }
                    //删除excel文件
                    unlink($file_name);
                    if ($num > 0) {
                        $this->success('导入成功' . $num . '条数据', url('teacher/index'), 30);
                    } else {
                        $this->error('导入第' . $num . '条失败');
                    }


                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            }
        }
    }

    public function deleteTag(){
        $id = $this->request->param('id');
        if ($id){
            $find = Db::name("tags")->where('id',$id)->delete();
            if ($find === false){
                $data['code'] = 0;
                $data['msg'] = '删除失败';
            }else{
                $data['code'] = 1;
                $data['msg'] = '删除成功';
            }

            return $data;
        }else{
            $data['code'] = 0;
            $data['msg'] = '删除失败111';
            return $data;
        }
    }

}
